import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL
})

// 请求拦截器
request.interceptors.request.use(function (config) {
  const userStore = useUserStore()
  config.headers = {
    ...config.headers,
    Authorization: userStore.$state.token
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(response => {
  const res = response.data
  if (res.meta.status === 200 || res.meta.status === 201) {
    return response
  } else if (res.meta.status === 403 || res.meta.status === 401) {
    ElMessage.error('鉴权超时')
    return Promise.reject(res.meta.msg)
  } else {
    ElMessage.error(`${res.meta.msg}`)
    return Promise.reject(res.meta.msg)
  }
})

export default <T>(config: AxiosRequestConfig) => {
  return request(config).then(res => {
    return (res.data.data || res.data) as T
  })
}
